package com.jy.api.controller;

import com.jy.api.dao.PaymentDao;
import com.jy.api.domain.Payment;
import com.jy.api.domain.SwiftPassMicroPayBaseResult;
import com.jy.api.domain.SwiftPassReversePaymentResult;
import com.jy.api.service.PaymentService;
import com.jy.api.signUpReq.web.WebCancelPayReq;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;

/**
 * Created by hanxi on 2018/8/17.
 */
@RestController
@RequestMapping(value = "v1", produces = "application/json;charset=utf-8")
public class PaymentController {
    private PaymentService paymentService;
    private PaymentDao paymentDao;

    /**
     * 新增刷卡支付
     *
     * @param orderId
     * @param body
     * @return
     */
    /*@PostMapping(path = "/orders/{orderId}/micro-pay", consumes = "application/json")
    public ResponseEntity postMicroPayment(@PathVariable String orderId, @RequestBody MicroPayBody body) {
        SwiftPassMicroPayBaseResult result = paymentService.microPay(orderId, body.authCode);
        if (result.isSuccess()) {
            return ResponseEntity.ok().location(URI.create("/v1/payments/" + result.getTransactionId())).build();
        } else if (result.isNeedQuery()) {
            return ResponseEntity.accepted().build();
        } else if (result.isFailed()) {
            return ResponseEntity.badRequest().body("支付失败，请让客户更换支付方式");
        } else {
            throw new RuntimeException("支付结果未知，请稍后到订单列表查看支付状态");
        }
    }*/

    /**
     * 查询支付信息
     *
     * @param id
     * @return
     */
    @GetMapping(path = "/payments/{id}")
    public Payment get(@PathVariable String id) {
        return paymentDao.findOne(id);
    }

    /**
     * 取消进行中的在线支付请求
     *
     * @param orderId
     * @return
     */
    @DeleteMapping(path = "/orders/{orderId}/third-party-payment")
    public ResponseEntity cancelOnlinePayment(@PathVariable String orderId) {
        WebCancelPayReq req = new WebCancelPayReq();
        SwiftPassReversePaymentResult result = paymentService.cancelThirdPartyPayment(orderId,req);
        if (result.isSuccess()) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.badRequest().body(result.getErrMsg());
        }
    }

    @PostMapping(path = "/pay/fill-payment-channel")
    public void fillPaymentChannel(){
        paymentService.fillPaymentChannel();
    }

    @Autowired
    public void setPaymentService(PaymentService paymentService) {
        this.paymentService = paymentService;
    }

    @Autowired
    public void setPaymentDao(PaymentDao paymentDao) {
        this.paymentDao = paymentDao;
    }

    @Data
    private class MicroPayBody {
        private String authCode;
    }
}
